package com.onenine.app.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.TextUtils;
import android.util.Pair;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.onenine.app.R;
import com.onenine.app.activity.GameRunningTextActivity;
import com.onenine.app.activity.GameRunningVideoActivity;
import com.onenine.app.activity.GameRunningVoiceActivity;
import com.onenine.app.adapter.GameRoomAdapter;
import com.onenine.app.event.GameFilterEvent;
import com.onenine.app.event.RefreshEvent;
import com.onenine.app.model.GameCategory;
import com.onenine.app.model.GameRoom;
import com.onenine.app.request.GetGameRoomRequest;
import com.onenine.app.response.ConvertUidResponse;
import com.onenine.app.response.GetGameRoomResponse;
import com.onenine.app.utils.CDataProcessor;
import com.onenine.app.utils.DataType;
import com.onenine.app.utils.UrlConfig;
import com.onenine.base.base.BasePageListFragment;
import com.onenine.base.okhttp.OkCallback;
import com.onenine.base.okhttp.OkRequest;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.ItemSpacesDecoration;
import com.onenine.base.utils.Toasty;
import com.onenine.base.view.PullRefreshRecyclerView;
import com.onenine.chat.rongcloud.RcUser;
import com.onenine.common.util.ApUtils;
import com.onenine.common.util.ScreenUtils;
import com.onenine.common.util.SizeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class GameCategoryFragment extends BasePageListFragment {

    public static GameCategoryFragment newInstance(GameCategory gameCategory) {
        GameCategoryFragment fragment = new GameCategoryFragment();
        Bundle args = new Bundle();
        args.putSerializable("data", gameCategory);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayout() {
        return R.layout.layout_pull_refresh_view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected Pair<PullRefreshRecyclerView, RecyclerView.Adapter> initPullRefreshView(View view) {
        int padding = SizeUtils.dp2px(5);
        mPullRefreshView = view.findViewById(R.id.pull_to_refresh_layout);
        mPullRefreshView.setRefreshBackgroundColor(ActivityCompat.getColor(ApUtils.getApp(), R.color.white));
        mPullRefreshView.setRecyclerViewPadding(padding);
        mPullRefreshView.addItemDecoration(new ItemSpacesDecoration(padding, padding, padding, padding));
        return new Pair(mPullRefreshView, new GameRoomAdapter((ScreenUtils.getScreenWidth() - 6 * padding) / 2));
    }

    @Override
    protected void loadPageData(int pageNum) {
        GetGameRoomRequest request = new GetGameRoomRequest();
        request.setUserId(RcUser.getInstance().getUserId());
        request.setPageNum(pageNum);
        request.setPageSize(AppConfig.PAGE_SIZE);
        if (GameCenterFragment.sGameFilter != null) {
            request.setBetNum(GameCenterFragment.sGameFilter.betAmountPair.second);
            request.setGamePattern(GameCenterFragment.sGameFilter.modePair.second);
            request.setPlayerRestrict(GameCenterFragment.sGameFilter.limitPair.second);
            if (GameCenterFragment.sGameFilter.gameCategory != null) {
                request.setGameName(GameCenterFragment.sGameFilter.gameCategory.getGameName());
            }
        }
        OkRequest.getInstance().withUrl(UrlConfig.GET_GAME_ROOM).withRequest(request)
                .doRequest(FriendAttentionFragment.class.getSimpleName(), new OkCallback<GetGameRoomResponse>() {
                    @Override
                    public void onResponse(GetGameRoomResponse response, String srcData) {
                        dismissRefreshStatus();
                        if (response.isSuccess()) {
                            notifyDataSuccess(response.getGameRoomList());
                        } else {
                            notifyDataFailure();
                        }
                    }
                });
    }

    @Override
    public void initData() {
        super.initData();
        loadPageData(1);
    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        GameRoom gameRoom = (GameRoom) adapter.getItem(position);
        if (!TextUtils.equals(RcUser.getInstance()
                .getUserId(), gameRoom.getUserId())) {
            //非本人创建房间
            if (gameRoom.getPlayerRestrict() == DataType.SEX_MALE
                    && RcUser.getInstance().getSex() == DataType.SEX_FEMALE) {
                //限男
                Toasty.showNormal(R.string.game_player_limit_male);
                return;
            }
            if (gameRoom.getPlayerRestrict() == DataType.SEX_FEMALE
                    && RcUser.getInstance().getSex() == DataType.SEX_MALE) {
                //限女
                Toasty.showNormal(R.string.game_player_limit_female);
                return;
            }
        }
        String uid = RcUser.getInstance().getUserPkId();
        if (TextUtils.isEmpty(uid)) {
            CDataProcessor.convertUserId2UserPkId(RcUser.getInstance().getUserId(), new OkCallback<ConvertUidResponse>() {
                @Override
                public void onResponse(ConvertUidResponse response, String srcData) {
                    if (response.isSuccess()) {
                        joinGamePlay(response.getObjId(), gameRoom);
                    } else {
                        Toasty.showNormal(response.getMessage());
                    }
                }
            });
        } else {
            joinGamePlay(uid, gameRoom);
        }
    }

    /**
     * 进入游戏房间
     *
     * @param uid
     * @param gameRoom
     */
    private void joinGamePlay(String uid, GameRoom gameRoom) {
        switch (gameRoom.getGamePattern()) {
            case GameRoom.GAME_MODE_TEXT:
                GameRunningTextActivity.launchActivity(getActivity(), gameRoom.getGameUrl()
                        , gameRoom.getGameRoomPkId(), uid);
                break;
            case GameRoom.GAME_MODE_VOICE:
                GameRunningVoiceActivity.launchActivity(getActivity(), gameRoom.getGameUrl()
                        , gameRoom.getGameRoomPkId(), uid);
                break;
            case GameRoom.GAME_MODE_VIDEO:
                GameRunningVideoActivity.launchActivity(getActivity(), gameRoom.getGameUrl()
                        , gameRoom.getGameRoomPkId(), uid);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshEvent event) {
        if (event.getType() == DataType.REFRESH_GAME_ROOM_CREATED) {
            //创建房间刷新
            onRefresh();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GameFilterEvent event) {
        if (event != null) {
            //条件筛选刷新
            GameCenterFragment.sGameFilter = event;
            onRefresh();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}
